<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="alternate" href="/atom.xml" title="刘攀的个人专栏" type="application/atom+xml">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://liupan.run').hostname,
    root: '/',
    scheme: 'Pisces',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"right","Pisces | Gemini":240,"display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="Flask中.env加载变量注意事项">
<meta name="keywords" content="flask,.env">
<meta property="og:type" content="article">
<meta property="og:title" content="016-Flask中.env加载变量注意事项">
<meta property="og:url" content="http:&#x2F;&#x2F;liupan.run&#x2F;2020&#x2F;01&#x2F;02&#x2F;016-Flask%E4%B8%AD.env%E5%8A%A0%E8%BD%BD%E5%8F%98%E9%87%8F%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9&#x2F;index.html">
<meta property="og:site_name" content="刘攀的个人专栏">
<meta property="og:description" content="Flask中.env加载变量注意事项">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-01-02T11:44:32.592Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://liupan.run/2020/01/02/016-Flask%E4%B8%AD.env%E5%8A%A0%E8%BD%BD%E5%8F%98%E9%87%8F%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>016-Flask中.env加载变量注意事项 | 刘攀的个人专栏</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">刘攀的个人专栏</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">面朝大海,春暖花开</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">28</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">0</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">20</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://liupan.run/2020/01/02/016-Flask%E4%B8%AD.env%E5%8A%A0%E8%BD%BD%E5%8F%98%E9%87%8F%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="liupan">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="刘攀的个人专栏">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          016-Flask中.env加载变量注意事项
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-01-02 09:01:01 / 修改时间：19:44:32" itemprop="dateCreated datePublished" datetime="2020-01-02T09:01:01+08:00">2020-01-02</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<p>Flask中.env加载变量注意事项</p>
</blockquote>
<a id="more"></a>

<h2 id="问题点"><a href="#问题点" class="headerlink" title="问题点"></a>问题点</h2><h3 id="坑一：python-dotenv加载的Value都是字符串类型"><a href="#坑一：python-dotenv加载的Value都是字符串类型" class="headerlink" title="坑一：python-dotenv加载的Value都是字符串类型"></a>坑一：python-dotenv加载的Value都是字符串类型</h3><p><strong>python-dotenv加载的Value都是字符串类型</strong>（<code>python-dotenv</code>版本0.10.1），因此导致整型、浮点型和布尔类型需要转换一下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># `.env`</span><br><span class="line">MAIL_PORT = 465</span><br><span class="line">MAIL_USE_SSL = false</span><br><span class="line">MAIL_USE_TLS = true</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># settings.py</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BaseConfig</span><span class="params">(object)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    MAIL_PORT = int(os.getenv(<span class="string">'MAIL_PORT'</span>, default=<span class="number">587</span>))</span><br><span class="line">    MAIL_USE_SSL = <span class="literal">True</span> <span class="keyword">if</span> <span class="string">'true'</span> == os.getenv(<span class="string">'MAIL_USE_SSL'</span>) <span class="keyword">else</span> <span class="literal">False</span></span><br><span class="line">    MAIL_USE_TLS = <span class="literal">True</span> <span class="keyword">if</span> <span class="string">'true'</span> == os.getenv(<span class="string">'MAIL_USE_TLS'</span>) <span class="keyword">else</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>

<h3 id="坑二：pipenv影响了flask加载-env环境变量"><a href="#坑二：pipenv影响了flask加载-env环境变量" class="headerlink" title="坑二：pipenv影响了flask加载.env环境变量"></a>坑二：pipenv影响了flask加载.env环境变量</h3><p>和pipenv有关，众所周知Flask项目可以通过.env加载环境变量，但是，pipenv也可以通过.env加载环境变量！问题就出现了，进入pipenv shell虚拟环境后，修改.env环境变量后再启动Flask app：flask run，Flask还是用了原来的环境变量！！！</p>
<p>究其原因，是pipenv shell加载了环境变量并进行了缓存，然后flask加载环境变量时没有进行覆盖</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash"> pipenv shell</span></span><br><span class="line">Loading .env environment variables…</span><br><span class="line">Launching subshell in virtual environment…</span><br><span class="line">...</span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> flask run  <span class="comment"># 正常预期</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 停止flask，修改 .env 环境变量，保存</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> flask run  <span class="comment"># 没达到修改变量后的预期效果</span></span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>尤其是部署Flask到服务器后，以下步骤肯定有问题的！！！</p>
<figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ pipenv <span class="keyword">shell</span></span><br><span class="line"><span class="bash">$ vim .env</span></span><br><span class="line">...</span><br><span class="line">$ flask <span class="keyword">run</span></span><br></pre></td></tr></table></figure>
</blockquote>
<h2 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h2><h3 id="方案一：重进pipenv-shell"><a href="#方案一：重进pipenv-shell" class="headerlink" title="方案一：重进pipenv shell"></a>方案一：重进pipenv shell</h3><p>一种解决方案就是退出<code>pipenv shell</code>环境再进入：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash"> pipenv shell</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="comment"># 编辑 .env</span></span></span><br><span class="line">...</span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">exit</span></span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> pipenv shell</span></span><br></pre></td></tr></table></figure>

<p>另一个解决方案是在主目录下新建一个<code>app.py</code>，拷贝下面代码，以后使用<code>python app.py</code>启动。</p>
<h3 id="方案二：新建并使用app-py启动"><a href="#方案二：新建并使用app-py启动" class="headerlink" title="方案二：新建并使用app.py启动"></a>方案二：新建并使用app.py启动</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="string">python app.py</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">from</span> dotenv <span class="keyword">import</span> load_dotenv</span><br><span class="line">dotenv_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), <span class="string">'.env'</span>)</span><br><span class="line"><span class="keyword">if</span> os.path.exists(dotenv_path):</span><br><span class="line">    load_dotenv(dotenv_path, override=<span class="literal">True</span>)  <span class="comment">#  override=True: 覆写已存在的变量</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> apps.web <span class="keyword">import</span> create_app</span><br><span class="line"></span><br><span class="line">app = create_app()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</span><br><span class="line">    app.run()</span><br></pre></td></tr></table></figure>
<h3 id="方案三：设置PIPENV-DONT-LOAD-ENV-1"><a href="#方案三：设置PIPENV-DONT-LOAD-ENV-1" class="headerlink" title="方案三：设置PIPENV_DONT_LOAD_ENV=1"></a>方案三：设置PIPENV_DONT_LOAD_ENV=1</h3><p>还有一个方案是设置<code>PIPENV_DONT_LOAD_ENV=1</code>，不让pipenv加载<code>.env</code>。</p>
<p>PowerShell示例（注意没有了<code>Loading .env environment variables…</code>信息）：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; $env:PIPENV_DONT_LOAD_ENV=<span class="number">1</span></span><br><span class="line">&gt; pipenv shell</span><br><span class="line">Launching subshell <span class="keyword">in</span> virtual environment…</span><br><span class="line">Windows PowerShell</span><br><span class="line">...</span><br></pre></td></tr></table></figure>



<h3 id="方案四：使用-flaskenv"><a href="#方案四：使用-flaskenv" class="headerlink" title="方案四：使用.flaskenv"></a>方案四：使用.flaskenv</h3><p><code>pipenv shell</code>不会从<code>.flaskenv</code>加载变量，所以如果有经常需要修改的环境变量也可以放在<code>.flaskenv</code>。但是我感觉一点也不优雅，因为我习惯把<code>.flaskenv</code>也提交到仓库，而留下<code>.env</code>在部署端客制化。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/flask/" rel="tag"># flask</a>
              <a href="/tags/env/" rel="tag"># .env</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/01/01/014-JS%E9%9A%8F%E6%9C%BA%E4%B8%AD%E6%96%87%E5%AD%97%E7%AC%A6%E5%8F%8AVue%E4%B8%8EFlask%E5%AD%97%E7%95%8C%E7%AC%A6%E4%BF%AE%E6%94%B9/" rel="prev" title="014-JS随机中文字符及Vue与Flask字界符修改">
      <i class="fa fa-chevron-left"></i> 014-JS随机中文字符及Vue与Flask字界符修改
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/01/03/017-VSCode%E6%8F%92%E4%BB%B6ProjectsManager/" rel="next" title="017-VSCode插件ProjectsManager">
      017-VSCode插件ProjectsManager <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#问题点"><span class="nav-text">问题点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#坑一：python-dotenv加载的Value都是字符串类型"><span class="nav-text">坑一：python-dotenv加载的Value都是字符串类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#坑二：pipenv影响了flask加载-env环境变量"><span class="nav-text">坑二：pipenv影响了flask加载.env环境变量</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#解决方案"><span class="nav-text">解决方案</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方案一：重进pipenv-shell"><span class="nav-text">方案一：重进pipenv shell</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方案二：新建并使用app-py启动"><span class="nav-text">方案二：新建并使用app.py启动</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方案三：设置PIPENV-DONT-LOAD-ENV-1"><span class="nav-text">方案三：设置PIPENV_DONT_LOAD_ENV=1</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方案四：使用-flaskenv"><span class="nav-text">方案四：使用.flaskenv</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="liupan"
      src="/images/avatar.gif">
  <p class="site-author-name" itemprop="name">liupan</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">20</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">28</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/facetothesea" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;facetothesea" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/mailto:hbxgliupan@sina.com" title="E-Mail → mailto:hbxgliupan@sina.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">liupan</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.0.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.5.0
  </div>

        








        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>



  




  <script src="/js/local-search.js"></script>













  

  

  

</body>
</html>
